package utils

import (
	"bytes"
	"os"
	"os/exec"
	"runtime"
	"runtime/pprof"
	"time"
)

/** 需要系统权限 */
func SetSystemTime(t time.Time) error {
	if runtime.GOOS == "windows" {
		hms := t.Format("15:04:05.999999999") // hour-minute-second
		err := exec.Command("cmd", "/c", "time", hms).Run()
		if err != nil {
			return err
		}

		date := t.Format("2006-01-02")
		err = exec.Command("cmd", "/c", "date", date).Run()
		if err != nil {
			return err
		}

		return nil

	} else {

		cmd := exec.Command("date", "-s", t.Format("2006-01-02 15:04:05.999999999"))
		err := cmd.Run()
		if err != nil {
			return err
		}

		return nil
	}
}

var (
	dockerByte []byte = []byte("docker")
)

func IsInDocker() bool {
	if _, err := os.Stat("/.dockerenv"); err == nil {
		return true
	}
	bt := make([]byte, 1024)
	if f, err := os.OpenFile("/proc/self/cgroup", os.O_RDONLY, os.ModePerm); err == nil {
		rLen, err := f.Read(bt)
		f.Close()
		if err == nil {
			return bytes.Index(bt[:rLen], dockerByte) > -1
		}
	}
	if f, err := os.OpenFile("/proc/1/cgroup", os.O_RDONLY, os.ModePerm); err == nil {
		rLen, err := f.Read(bt)
		f.Close()
		if err == nil {
			return bytes.Index(bt[:rLen], dockerByte) > -1
		}
	}
	return false
}

func StatRuntimeInfo() string {
	var memStats runtime.MemStats
	var sb BytesBuilder
	runtime.ReadMemStats(&memStats)
	threadProfile := pprof.Lookup("threadcreate")
	curThreadCount := threadProfile.Count()
	//maxThreadCount := curThreadCount
	//threadCount := curThreadCount
	numGoRoutine := runtime.NumGoroutine() //初始的数量

	sb.Appendf("内存占用:%s, 存活对象:%d, HeapAlloc:%s, HeapObjects:%d\r\n",
		HumanFilesizeU(memStats.Sys), memStats.Mallocs-memStats.Frees, HumanFilesizeU(memStats.HeapAlloc), memStats.HeapObjects)

	sb.Appendf("上次回收时间：%s，垃圾回收占用服务CPU时间比：%.1f，总STW：%v, Goroutine数量：%d,当前线程数量：%d\r\n",
		DateTimeString2(time.Unix(0, int64(memStats.LastGC))), memStats.GCCPUFraction, time.Duration(memStats.PauseTotalNs),
		numGoRoutine, curThreadCount)

	return sb.String()
}
